from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse, JsonResponse
from django_redis import get_redis_connection
import random
from demo.libs.captcha.captcha import captcha
from demo.libs.yuntongxun.ccp_sms import CCP
import logging
from celery_tasks.sms.tasks import ccp_send_sms_code

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        conn = get_redis_connection('verify_code')
        try:
            conn.setex(
                "img_%s" % uuid,
                300, text
            )
        except Exception as e:
            print(e)
            logger.error(e)
        return HttpResponse(image, content_type='image/jpg')


import re


class SMSCodeView(View):
    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code, uuid]):
            return JsonResponse({
                'code': 400,
                'errmsg': '参数缺少'
            }, status=400)
        if not re.match(r'^\w{4}$', image_code):
            return JsonResponse({
                'code': 400,
                'errmsg': '图片参数错误'
            }, status=400)
        if not re.match(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$', uuid):
            return JsonResponse({
                'code': 400,
                'errmsg': 'uuid格式错误'
            }, status=400)
        conn = get_redis_connection('verify_code')
        image_code_from_redis = conn.get("img_%s" % uuid)
        if not image_code_from_redis:
            return JsonResponse({
                'code': 400,
                'errmsg': '图形验证码错误'
            }, status=400)
        conn = get_redis_connection('sms_code')
        flag = conn.get('flag_%s' % mobile)
        if flag:
            return JsonResponse({
                'code': 400,
                'errmsg': '请勿重复发送短信'
            }, status=400)
        sms_code = "%06d" % random.randint(0, 999999)
        print('手机验证码', sms_code)

        p = conn.pipeline()
        p.setex(
            'sms_%s' % mobile,
            300,
            sms_code
        )
        p.setex(
            'flag_%s' % mobile,
            60,
            '1'
        )
        p.execute()
        ccp_send_sms_code.delay(mobile, sms_code)

        return JsonResponse({
            'code': 0,
            'errmsg': 'OK'
        })
